import type { FormInstance } from 'element-plus';
import { reactive, ref, watch } from 'vue';

import { useUserStore } from '@/store/user';

interface Form {
  username: string;
  password: string;
  code: string;
  remember: boolean;
  way: string;
}

export default function useForm() {
  const userStore = useUserStore();
  const loginForm = ref<FormInstance>();
  const form = reactive<Form>({
    username: '',
    password: '',
    remember: true,
    code: '',
    way: 'user',
  });

  const rules = {
    username: [
      {
        required: true,
        message: '请输入账号',
        trigger: 'blur',
      },
    ],
    password: [
      {
        required: true,
        message: '请输入密码',
        trigger: 'blur',
      },
    ],
  };

  watch(
    () => form.username,
    (val) => {
      const index = userStore.rememberInfo.findIndex((item) => item.username === val);
      if (index !== -1) form.password = userStore.rememberInfo[index].password;
    },
  );

  /**
   * 登录
   * @param formEl form表单
   * @param fn 刷新code函数
   * @returns
   */
  const onSubmit = async (formEl: FormInstance | undefined, fn: Function) => {
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        try {
          await userStore.login(form);
        } catch (error) {
          fn();
        }
      } else {
        console.log('error submit!', fields);
      }
    });
  };

  return {
    form,
    rules,
    loginForm,
    onSubmit,
  };
}
